﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebCam_Capture;
using System.Windows.Media.Imaging;

namespace MontagsmalerApp.Utils
{
  public class WebCam
  {
    private WebCamCapture webcam;
    private System.Windows.Controls.Image _FrameImage;
    private int FrameNumber = 30;
    public void InitializeWebCam(ref System.Windows.Controls.Image ImageControl)
    {
      webcam = new WebCamCapture();
      webcam.FrameNumber = ((ulong)(0ul));
      webcam.TimeToCapture_milliseconds = FrameNumber;
      webcam.ImageCaptured += new WebCamCapture.WebCamEventHandler(webcam_ImageCaptured);
      _FrameImage = ImageControl;
    }

    void webcam_ImageCaptured(object source, WebcamEventArgs e)
    {
      _FrameImage.Source = LoadBitmap((System.Drawing.Bitmap)e.WebCamImage);
    }

    public void Start()
    {
      webcam.TimeToCapture_milliseconds = FrameNumber;
      webcam.Start(0);
    }

    public void Stop()
    {
      webcam.Stop();
    }

    public void Continue()
    {
      // change the capture time frame
      webcam.TimeToCapture_milliseconds = FrameNumber;

      // resume the video capture from the stop
      webcam.Start(this.webcam.FrameNumber);
    }

    public void ResolutionSetting()
    {
      webcam.Config();
    }

    public void AdvanceSetting()
    {
      webcam.Config2();
    }

    //Block Memory Leak
    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr handle);
    public static BitmapSource bs;
    public static IntPtr ip;
    public static BitmapSource LoadBitmap(System.Drawing.Bitmap source)
    {
      ip = source.GetHbitmap();
      bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, System.Windows.Int32Rect.Empty,
      System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

      DeleteObject(ip);

      return bs;
    }
  }
}
